package com.example.dubbo.service.business.impl.demo;

import com.example.common.vo.R;
import com.example.dubbo.aip.demo.AccountTblService;
import com.example.dubbo.aip.demo.BusinessService;
import com.example.dubbo.aip.demo.OrderTblService;
import com.example.dubbo.aip.demo.StorageTblService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;

/**
 * 处理业务 -实现类
 *
 * @author NiJo_H
 * @version 1.0
 */
@Slf4j
@Service(version = "1.0.0", timeout = 30000)
public class BusinessServiceImpl implements BusinessService {

    //账户相关
    @Reference(version = "1.0.0")
    private AccountTblService accountTblService;

    //订单类
    @Reference(version = "1.0.0")
    private OrderTblService orderTblService;

    //库存类
    @Reference(version = "1.0.0")
    private StorageTblService storageTblService;


    @GlobalTransactional(timeoutMills = 60000)
    @Override
    public R<String> handleBusiness() {
        log.info("全局事务开启-----{}", RootContext.getXID());
        //创建订单
        orderTblService.createOrder();
        //核减库存
        storageTblService.subtractStorage();
        //核减账户
        accountTblService.subtractAccount();
        if (true) {
            throw new NullPointerException("开始回滚");
        }
        return R.ok("订单下定成功...等待配送");
    }

    @Override
    public R<Void> handleFechargeAccount(Integer cnt) {
        boolean result = false;
        while (!result) {
            result = accountTblService.fechargeAccount(cnt);
        }
        return R.ok();
    }
}
